<?php
include_once "book.php";
include_once "settings.php";
include_once "shingles.php";

// variable initializing
$bookQuery = array();
$sequenceQuery = array();
$genreQuery = array();
$authorQuery = array();
$translatorQuery = array();

/*
 *
 * Functions Section
 *
 * ************************************************************************/

function moveImportedFileToStorage($IMPORT_DIR, $BOOK_DIR, $IMPORT_LOG_FILE, $currentFileName)
{

	// error/warnings/notices OFF (folder already exists)
	error_reporting(0);
	$era=error_get_last();
	print2log($IMPORT_LOG_FILE, implode(", ", $era));

	mkdir($BOOK_DIR . mb_substr($currentFileName,0,2));

	// error/warnings/notices ON
	error_reporting(-1);

	$srcFileName = $IMPORT_DIR . $currentFileName ;
	$targetFileName = $BOOK_DIR . mb_substr($currentFileName,0,2)."/".$currentFileName ;

	rename($srcFileName,$targetFileName);

	print2log($IMPORT_LOG_FILE, "File ".$srcFileName." moved to: ".$targetFileName) ;

}
// exctract Cover Page and return cover page filename.
function getCover($COVER_DIR, $currentInportedBook)
{
	if (isset($currentInportedBook->binary) and $currentInportedBook->binary != "default.jpg")
	{
		// extract and copy cover picture to ./cover dir
		$currentBookCoverFileName = $currentInportedBook->pureFileName."_cover.jpg" ;
		$currentCoverFileHandle = fopen($COVER_DIR.$currentBookCoverFileName, "w+");
		fwrite($currentCoverFileHandle, base64_decode($currentInportedBook->binary));
		fclose ($currentCoverFileHandle) ;
		return $currentBookCoverFileName ;
	}
	else
	{
		return "default.jpg";
	}
}


// build book query
function getBookQuery($connection, $currentSequence, $currentInportedBook)
{
	return "('".
			$currentSequence. "','".
			$currentInportedBook->flibustaBookID . "','".
			$currentInportedBook->fileSize ."','".
			$connection->real_escape_string($currentInportedBook->pureFileName) ."','".
			$currentInportedBook->coverpage ."','".
			$currentInportedBook->bookType ."','".
			$connection->real_escape_string($currentInportedBook->book_title) ."','".
			$connection->real_escape_string($currentInportedBook->keywords) ."','".
			$connection->real_escape_string($currentInportedBook->annotation)."','".
			$connection->real_escape_string($currentInportedBook->lang) ."','".
			$connection->real_escape_string($currentInportedBook->srcLang)	."','".
			$connection->real_escape_string($currentInportedBook->date)	."','".
			$connection->real_escape_string($currentInportedBook->publisherBookName)."','".
			$connection->real_escape_string($currentInportedBook->publisherPublisher)."','".
			$connection->real_escape_string($currentInportedBook->publisherCity)."','".
			$connection->real_escape_string($currentInportedBook->publisherYear)."','".
			$connection->real_escape_string($currentInportedBook->publisherISBN).
			"')" . PHP_EOL;
}

// build sequence query
function getSequnceQuery($connection, $currentSequence, $currentInportedBook)
{
	$sequenceQuery = array();

	if (sizeof($currentInportedBook->sequence))
	{
		if (is_array($currentInportedBook->sequence))
		{
			foreach ($currentInportedBook->sequence as $currentSeq)
			{
				$sequenceQuery[] = "('".
						$currentSequence. "','".
						$connection->real_escape_string(trim($currentSeq['name'])). "','".
						$connection->real_escape_string(trim($currentSeq['number'])).
						"')";
			}
		}
	}
	else
	{
		$sequenceQuery[] = "('".$currentSequence."',null, null)";
	}
	return $sequenceQuery ;
}

// build genre query
function getGenreQuery($connection, $currentSequence, $currentInportedBook)
{
	$genreQuery = array();
	if ($currentInportedBook->genre)
	{
		if (is_array($currentInportedBook->genre))
		{
			foreach ($currentInportedBook->genre as $currentGenre)
			{
				$genreQuery[] = "('".
						$currentSequence. "','".
						$currentGenre .
						"')";
			}
		}
		else
		{
			$genreQuery[] = "('". $currentSequence. "','". $connection->real_escape_string(trim($currentInportedBook->genre)) . "')";

		}

	}
	else
	{
		$genreQuery[] = "('". $currentSequence. "','unknown')";
	}

	return $genreQuery ;
}

// build author query
function getAuthorQuery($connection, $currentSequence, $currentInportedBook)
{
	$authorQuery = array();

	foreach ($currentInportedBook->authorName as $currentAuthor)
	{
		$authorQuery[] = "('".
				$currentSequence. "','".
				$connection->real_escape_string(trim($currentAuthor['first-name'])). "','".
				$connection->real_escape_string(trim($currentAuthor['middle-name'])). "','".
				$connection->real_escape_string(trim($currentAuthor['last-name'])). "','".
				$connection->real_escape_string(trim($currentAuthor['nickname'])). "','".
				$connection->real_escape_string(trim($currentAuthor['email'])).
				"')";
	}
	return $authorQuery ;
}

// build translator query
function getTranslatorQuery($connection, $currentSequence, $currentInportedBook)
{
	$translatorQuery = array();

	if (sizeof($currentInportedBook->translatorName) > 0)
	{
		foreach ($currentInportedBook->translatorName as $currentTranslator)
		{
			$translatorQuery[] = "('".
					$currentSequence. "','".
					$connection->real_escape_string(trim($currentTranslator['first-name'])). "','".
					$connection->real_escape_string(trim($currentTranslator['middle-name'])). "','".
					$connection->real_escape_string(trim($currentTranslator['last-name'])). "','".
					$connection->real_escape_string(trim($currentTranslator['nickname'])). "','".
					$connection->real_escape_string(trim($currentTranslator['email'])).
					"')";
		}
	}
	else
	{
		$translatorQuery[] = "('". $currentSequence."',null, null, null, null, null)";

	}
	return $translatorQuery ;
}

function getShingleQuery($connection, $currentSequence, $currentInportedBook, $stopWords)
{
	$inputText = $currentInportedBook->body;

	$shingleQuery = "('". $currentSequence. "','". implode(" ",shingleCalc($inputText, $stopWords, 9)) . "')";

return $shingleQuery;
}

/*************************************************************************/


// Initial time stamp and log header

$time = microtime(true);
$today = date("Y-m-d H:i:s");                   // 2001-03-10 17:16:18 (the MySQL DATETIME format)
print2log($IMPORT_LOG_FILE, " ###########  Import starts " . $today . " ###########" . PHP_EOL) ;




/************  start *** connection to MySQL and initalizing vars. */
$connection = new mysqli($host, $user, $password, $dbname, $port, $socket);
if ($connection->connect_error) { die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error); }
$connection->set_charset("utf8");

// get sequnce, last inserted ID from book
$res = $connection->query('select max(bookID) from book');
$currentSequence = $res->fetch_array();
$currentSequence = $currentSequence[0];
$initialSequence = $currentSequence ;

// if first load - put current sequence number to zero - 0
if (!isset($currentSequence)) { $currentSequence = 0; } ;
/************ end *** connection to MySQL and initalizing vars. */


$currentDirContent = getFileListFromImportDir($IMPORT_DIR) ;
$books2import = sizeof($currentDirContent);

// taking next (free) bookID.
$currentSequence++;



/**********************************  MAIN cycle */
foreach ($currentDirContent as $currentBookFile)
{

   $currentInportedBook = new Book;
   $currentInportedBook->readDataFromFile($IMPORT_DIR.$currentBookFile) ;
   // Print/Log FB2 parsing log
   print2log($IMPORT_LOG_FILE, "Start working on - " . $currentSequence . " - " . $IMPORT_DIR . $currentBookFile . PHP_EOL . implode($currentInportedBook->FB_LOG,PHP_EOL) . PHP_EOL) ;

   	if ($currentInportedBook->status == "error")
   	{
   		print2log($IMPORT_LOG_FILE, "FATAL ERROR READING FILE (unknown encoding?)- " . $currentInportedBook->fileName . "SKIPPED!" . PHP_EOL) ;
   		continue;
   	}

		// если есть обложка - достать и сложить в covers.
		$currentInportedBook->coverpage = getCover($COVER_DIR, $currentInportedBook) ;

		// build book query
		$bookQuery = getBookQuery($connection, $currentSequence, $currentInportedBook) ;
		$connection->query('
				INSERT INTO `book`
				(
				`bookID`,
				`flibustaBookID`,
				`fileSize`,
				`fileName`,
				`coverFileName`,
				`fileType`,
				`title`,
				`keywords`,
				`annotation`,
				`lang`,
				`srcLang`,
				`date`,
				`publisherBookName`,
				`publisherPublisher`,
				`publisherCity`,
				`publisherYear`,
				`publisherISBN`
		)
				VALUES '. $bookQuery) ;

		if ($connection->connect_error) {
			die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
		}


		// build sequence query
		$sequenceQuery = array_merge($sequenceQuery, getSequnceQuery($connection, $currentSequence, $currentInportedBook)) ;
		$connection->query('INSERT INTO `sequence`
				(
				`bookID`,
				`sequenceName`,
				`sequenceNumber`
		)
				VALUES '.implode(',', $sequenceQuery));



		// build genre query
		$genreQuery = array_merge($genreQuery, getGenreQuery($connection, $currentSequence, $currentInportedBook)) ;
		$connection->query('INSERT INTO `genre`
				(
				`bookID`,
				`genreCode`
		)
				VALUES '.implode(',', $genreQuery));


		// build author query
		$authorQuery = array_merge($authorQuery, getAuthorQuery($connection, $currentSequence, $currentInportedBook));
		$connection->query('INSERT INTO `author`
				(
				`bookID`,
				`authorFirstName`,
				`authorMiddleName`,
				`authorLastName`,
				`authorNickName`,
				`authorEMail`
		)
				VALUES '.implode(',', $authorQuery));



		// build translator query
		$translatorQuery = array_merge($translatorQuery, getTranslatorQuery($connection, $currentSequence, $currentInportedBook)) ;
		$connection->query('INSERT INTO `translator`
				(
				`bookID`,
				`translatorFirstName`,
				`translatorMiddleName`,
				`translatorLastName`,
				`translatorNickName`,
				`translatorEMail`
		)
				VALUES '.implode(',', $translatorQuery));

		// build shinlge query
		$shingleQuery = getShingleQuery($connection, $currentSequence, $currentInportedBook, $stopWords) ;
		$connection->query('INSERT INTO `book_shingle`
				(
				`bookID`,
				`book_shingle_value`
		)
				VALUES '. $shingleQuery) ;

	moveImportedFileToStorage($IMPORT_DIR, $BOOK_DIR, $IMPORT_LOG_FILE, $currentInportedBook->pureFileName);

	$currentSequence++;
	unset($currentInportedBook);


}
/**********************************  MAIN cycle */

print2log($IMPORT_LOG_FILE, $currentSequence - $initialSequence - 1 . " Books was processed" . PHP_EOL) ;

/*
$connection->query('INSERT INTO `book_shingle`
		(
		`bookID`,
		`book_shingle_value`
)
		VALUES '.implode(',', $shingleQuery));
print2log($IMPORT_LOG_FILE, "shingle errors" . PHP_EOL . $connection->error . PHP_EOL) ;

$connection->query('INSERT INTO `genre`
		(
			`bookID`,
			`genreCode`
		)
		VALUES '.implode(',', $genreQuery));
print2log($IMPORT_LOG_FILE, "genre errors" . PHP_EOL . $connection->error . PHP_EOL) ;


$connection->query('INSERT INTO `author`
		(
			`bookID`,
			`authorFirstName`,
			`authorMiddleName`,
			`authorLastName`,
			`authorNickName`,
			`authorEMail`
		)
		VALUES '.implode(',', $authorQuery));
print2log($IMPORT_LOG_FILE, "author errors" . PHP_EOL . $connection->error . PHP_EOL) ;


if (sizeof($translatorQuery) > 0)
{
$connection->query('INSERT INTO `translator`
		(
			`bookID`,
			`translatorFirstName`,
			`translatorMiddleName`,
			`translatorLastName`,
			`translatorNickName`,
			`translatorEMail`
		)
		VALUES '.implode(',', $translatorQuery));
print2log($IMPORT_LOG_FILE, "translator errors" . PHP_EOL . $connection->error . PHP_EOL) ;
}


if (sizeof($sequenceQuery) > 0)
{
$connection->query('INSERT INTO `sequence`
		(
			`bookID`,
			`sequenceName`,
			`sequenceNumber`
		)
		VALUES '.implode(',', $sequenceQuery));

print2log($IMPORT_LOG_FILE, "sequence errors" . PHP_EOL . $connection->error . PHP_EOL) ;
}

$tmp = 'INSERT INTO `book`
		(
			`bookID`,
			`flibustaBookID`,
			`fileSize`,
			`fileName`,
			`coverFileName`,
			`fileType`,
			`title`,
			`keywords`,
			`annotation`,
			`lang`,
			`srcLang`,
			`date`,
			`publisherBookName`,
			`publisherPublisher`,
			`publisherCity`,
			`publisherYear`,
			`publisherISBN`
		)
		VALUES '.implode(',', $bookQuery);
$file = 'book.sql';
file_put_contents($file, $tmp);


$connection->query('
		INSERT INTO `book`
		(
			`bookID`,
			`flibustaBookID`,
			`fileSize`,
			`fileName`,
			`coverFileName`,
			`fileType`,
			`title`,
			`keywords`,
			`annotation`,
			`lang`,
			`srcLang`,
			`date`,
			`publisherBookName`,
			`publisherPublisher`,
			`publisherCity`,
			`publisherYear`,
			`publisherISBN`
		)
		VALUES '.implode(',', $bookQuery));

print2log($IMPORT_LOG_FILE, "books errors" . PHP_EOL . $connection->error . PHP_EOL ) ;
*/
$connection->close();



$time = abs(round($time - microtime(true),2));
print2log($IMPORT_LOG_FILE, $time . " sec". PHP_EOL . "all done" . PHP_EOL ) ;


?>